package com.vvv.designpattern.pay.strategy;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.vvv.designpattern.constants.Constants;
import com.vvv.designpattern.pojo.Order;

import java.util.HashMap;
import java.util.Map;

/**
 * @author vvv
 * @date 2023-11-22 15 02
 * discription策略模式：具体策略角色，是实现具体逻辑的类
 *
 * 这里使用new + 工厂类反射创建而不是@component + 工厂类直接注入，是因为前面的方式可以起到懒惰的作用
 */
public class AlipayStrategy implements PayStrategyInterface{
    @Override
    public String pay(Order order) {
        // 创建AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(
                Constants.ALIPAY_GATEWAY,
                Constants.APP_ID,
                Constants.APP_PRIVATE_KEY,
                "JSON",
                "UTF-8",
                Constants.ALIPAY_PUBLIC_KEY,
                Constants.SIGN_TYPE
        );
        // 设置请求参数
        AlipayTradePagePayRequest payRequest = new AlipayTradePagePayRequest();
        payRequest.setReturnUrl(Constants.CALLBACK_URL);
        Map<String, Object> params = new HashMap<>();
        params.put("out_trade_no", order.getOrderId());
        params.put("total_amount", order.getPrice());
        params.put("subject", "vvv");
        params.put("body", "商品描述");
        params.put("product_code", "FAST_INSTANT_TRADE_PAY");
        payRequest.setBizContent(JSONObject.toJSONString(params));
        // 请求
        try {
            // result 为支付宝的支付url连接，需要前端跳转到这个连接上完成支付操作
            String result = alipayClient.pageExecute(payRequest, "GET").getBody();
            return result;
        } catch (AlipayApiException e) {
            throw new UnsupportedOperationException("Alipay failed!" + e);
        }
    }
}
